package com.powergisol.gis.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.powergisol.gis.dto.SectionDTO;
import com.powergisol.gis.dto.VirtualDrillDTO;
import com.powergisol.gis.entity.*;
import com.powergisol.gis.geom.GeoLineString;
import com.powergisol.gis.geom.GeoPoint;
import com.powergisol.gis.service.*;
import com.powergisol.gis.util.FileUtil;
import com.powergisol.gis.util.Result;
import com.powergisol.gis.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TabZuanKongServiceImpl implements TabZuanKongService {

    @Autowired
    VirtualDrillService validationService;

    @Autowired
    SectionService sectionService;

    @Value("${ZKLX}")
    private String ZKLX;

    @Override
    public Result simulateZuanKong(SimulateZuanKongVo vo) {
        Result r = new Result();
        List<MoniZuankongVo> vos = new ArrayList<>();
        try {

            String userDir = System.getProperty("user.dir");
            String filePlanUrl = userDir+File.separator +"plane"+File.separator+vo.getUuid()+".json";
//            String filePlanUrl = "E:\\project\\plane\\857b62d0-86e9-11eb-b105-c99df67afc36.json";
            String plane = FileUtil.getContent(filePlanUrl);
            GeoPoint point = new GeoPoint(vo.getX(), vo.getY(), vo.getZ());

            List<VirtualDrillDTO> list = validationService.getIntersection(point, plane);
            if (list.isEmpty()) {
                return r;
            }
            //根据uuid查询岩层分层设置
            List<TabMarkerColor> listColors =getByJason(vo.getColorPath());

            Double tccdsd = 0d;//层底深度
            Double tchd = 0d;//岩层厚度
            Double zksd = 0d;
            String x = BigDecimal.valueOf(vo.getX()).setScale(6, BigDecimal.ROUND_HALF_UP).toString();
            x = x.substring(x.lastIndexOf(".") + 1, x.length());
            String zkbh = ZKLX + x;
            BigDecimal zkbg = new BigDecimal(vo.getZ()).setScale(6, BigDecimal.ROUND_HALF_UP);
            for (int i = list.size() - 1; i >= 0; i--) {
                if (i % 2 != 0) {
                    VirtualDrillDTO dto = list.get(i - 1);
                    tchd = list.get(i - 1).getGeoPoint().getZ() - list.get(i).getGeoPoint().getZ();
                    tccdsd = vo.getZ() - list.get(i).getGeoPoint().getZ();


                    MoniZuankongVo moniZuankongVo = new MoniZuankongVo();
                    moniZuankongVo.setTCHD(new BigDecimal(tchd).setScale(6, BigDecimal.ROUND_HALF_UP));
                    moniZuankongVo.setZKBG(zkbg);
                    moniZuankongVo.setZKBH(zkbh);
                    moniZuankongVo.setZKLX(ZKLX);
                    moniZuankongVo.setZKX(new BigDecimal(vo.getX()).setScale(6, BigDecimal.ROUND_HALF_UP));
                    moniZuankongVo.setZKY(new BigDecimal(vo.getY()).setScale(6, BigDecimal.ROUND_HALF_UP));
                    moniZuankongVo.setSettingId(vo.getSettingId());



                    zksd = zksd + tchd;
                    moniZuankongVo.setTCCDSD(new BigDecimal(tccdsd).setScale(6, BigDecimal.ROUND_HALF_UP));

                    String level = dto.getLevel() + "";
                    List<TabMarkerColor> configs = listColors.stream().filter((TabMarkerColor b) -> level.equals(b.getZkfc().toString()))
                            .collect(Collectors.toList());

                    moniZuankongVo.setTCMC(configs.get(0).getDrillMarker());
                    moniZuankongVo.setTCBH(configs.get(0).getTcbh());
                    moniZuankongVo.setTCSDCY(configs.get(0).getTcsdcy());
                    moniZuankongVo.setTCMS(configs.get(0).getTcms());
                    vos.add(moniZuankongVo);
                }

            }
            r.setData(vos);
        } catch (Exception e) {
            e.printStackTrace();
            e.getMessage();
            return r.failure(500, e.getMessage());
        }
        return r;
    }


    @Override
    public Result sliceZuanKong(SliceZuanKongVo vo) {
        Result r = new Result();
        try {
            List<GeoLineString> sections = new ArrayList<>();

            List<List<List<Double>>> list = vo.getPoint();

            for (List<List<Double>> dList : list) {

                GeoLineString line = new GeoLineString(dList.get(0).get(0), dList.get(0).get(1), dList.get(0).get(2), dList.get(1).get(0), dList.get(1).get(1), dList.get(1).get(2));
                sections.add(line);
            }
            String userDir = System.getProperty("user.dir");

            String filePlanUrl = userDir+File.separator +"plane"+File.separator+vo.getUuid()+".json";

//            String filePlanUrl = "E:\\project\\plane\\857b62d0-86e9-11eb-b105-c99df67afc36.json";
            String plane = FileUtil.getContent(filePlanUrl);

            List<SectionDTO> listDto = sectionService.createSectionByLine(sections, plane, null == vo.getHeight() ? 1000d : vo.getHeight());
            r.setData(listDto);
        } catch (IOException e) {
            e.printStackTrace();
            r.failure(500, "生成切面失败");
        }
        return r;
    }

    private List<TabMarkerColor> getByJason(String path){
        List<TabMarkerColor> colors = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        try {
            String data = FileUtil.getContent(path);
            if(StringUtils.isBlank(data)){
                Resource classPathResource = new ClassPathResource("json/color.json");
                InputStream inputStream = classPathResource.getInputStream();
                data = FileUtil.getDatafromFile(inputStream);
            }
            CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, TabMarkerColor.class);
            colors = mapper.readValue(data,listType);

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return colors;
    }

    public static void main(String[] args) {
        List<TabMarkerColor> colors = new ArrayList<>();
        ObjectMapper mapper = new ObjectMapper();
        Resource classPathResource = new ClassPathResource("json/color.json");
        try {
            InputStream inputStream = classPathResource.getInputStream();
            String data = FileUtil.getDatafromFile(inputStream);
            CollectionType listType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, TabMarkerColor.class);
            colors = mapper.readValue(data,listType);
            System.out.println(colors.get(0).getDrillMarker());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Object> getYcModel(String uuid){
        List<Object> resultList = new ArrayList<>();
        Map<String, Object> m = new HashMap<>();
        String userDir = System.getProperty("user.dir");
        String fileWallUrl = userDir+File.separator +"wall"+File.separator+uuid+".json";
        String filePlanUrl = userDir+File.separator +"plane"+File.separator+uuid+".json";
        m.put("wall", FileUtil.getContent(fileWallUrl));
        m.put("plane", FileUtil.getContent(filePlanUrl));
        resultList.add(m);
        return resultList;
    }

}
